import 'dart:async';
import 'dart:io';
import '../../xmpp_stone.dart';

/// @description XmppConnectionState改变监听处理器，传递message
/// @author ping
/// @data 2021/8/31
class MyConnectionStateChangedListener implements ConnectionStateChangedListener {

  final String TAG = 'MyConnectionStateChangedListener';

  Connection _connection;
  MessagesListener _messagesListener;
  StreamSubscription<String> subscription;

  MyConnectionStateChangedListener(Connection connection, MessagesListener messagesListener) {
    _connection = connection;
    _messagesListener = messagesListener;
    _connection.connectionStateStream.listen(onConnectionStateChanged);
  }

  @override
  void onConnectionStateChanged(XmppConnectionState state) {
    if (state == XmppConnectionState.Ready) {
      Log.d(TAG, 'Connected');
      var vCardManager = VCardManager(_connection);
      vCardManager.getSelfVCard().then((vCard) {
        if (vCard != null) {
          Log.d(TAG, 'Your info' + vCard.buildXmlString());
        }
      });
      var messageHandler = MessageHandler.getInstance(_connection);
      var rosterManager = RosterManager.getInstance(_connection);
      messageHandler.messagesStream.listen(_messagesListener.onNewMessage);
      sleep(const Duration(seconds: 1));
      // var receiver = 'test2@192.168.168.235';
      // var receiverJid = Jid.fromFullJid(receiver);
      // rosterManager.addRosterItem(Buddy(receiverJid)).then((result) {
      //   if (result.description != null) {
      //     Log.d(TAG, 'add roster' + result.description);
      //   }
      // });
      // sleep(const Duration(seconds: 1));
      // vCardManager.getVCardFor(receiverJid).then((vCard) {
      //   if (vCard != null) {
      //     Log.d(TAG, 'Receiver info' + vCard.buildXmlString());
      //     if (vCard != null && vCard.image != null) {
      //       var file = File('test456789.jpg')..writeAsBytesSync(image.encodeJpg(vCard.image));
      //       Log.d(TAG, 'IMAGE SAVED TO: ${file.path}');
      //     }
      //   }
      // });
      var presenceManager = PresenceManager.getInstance(_connection);
      presenceManager.presenceStream.listen(onPresence);
    }
  }

  void onPresence(PresenceData event) {
    Log.d(TAG, 'presence Event from ' + event.jid.fullJid + ' PRESENCE: ' + event.showElement.toString());
  }
}

